public with sharing class CustomOccupationLookupController 
{ 
    public Occupation__c occupation {get;set;} // new occupation to create
    
    public List<Occupation__c> results{get;set;} // search results
    public string searchString{get;set;} // search keyword
 
    public CustomOccupationLookupController() 
    {
        occupation = new Occupation__c();
        // get the current search string
        searchString = System.currentPageReference().getParameters().get('lksrch');
        runSearch();  
    }
 
    // performs the keyword search
    public PageReference search() 
    {
        runSearch();
        return null;
    }
 
    // prepare the query and issue the search command
    private void runSearch() 
    {
        // TODO prepare query string for complex serarches & prevent injections
        results = performSearch(searchString);               
    } 
 
    // run the search and return the records found. 
    private List<Occupation__c> performSearch(string searchString) 
    {
        String soql = 'SELECT id, name, Arabic_Occupation__c FROM Occupation__c';
        if(searchString != '' && searchString != null)
        {
            soql = soql +  ' WHERE name LIKE \'' + searchString +'%\'';
        }
        soql = soql + ' limit 50';
        System.debug(soql);
        return database.query(soql); 
    }
 
    // save the new occupation record
    public PageReference saveOccupation() 
    {
        if(occupation.Name != null)
        {
            if(occupation.Name.trim() != '')
            {
                insert occupation;
            
                // reset the occupation
                occupation = new Occupation__c();
            }
            else
            {
                ApexPages.Message error = new ApexPages.Message(ApexPages.Severity.ERROR, 'Invalid Name');
                ApexPages.AddMessage(error);
            }
        }
        else
        {
            ApexPages.Message error = new ApexPages.Message(ApexPages.Severity.ERROR, 'Invalid Name');
            ApexPages.AddMessage(error);
        }
        
        return null;
    }
 
    // used by the visualforce page to send the link to the right dom element
    public string getFormTag() 
    {
        return System.currentPageReference().getParameters().get('frm');
    }
 
    // used by the visualforce page to send the link to the right dom element for the text box
    public string getTextBox() 
    {
        return System.currentPageReference().getParameters().get('txt');
    }
}